<template>
    <view>
        <view class="login-bg">
			<uv-button  color="linear-gradient(to right, rgb(21, 200, 216), rgb(196, 204, 213))"  text="历史记录" @click="navigateToHistory"></uv-button>
			<view style="border-bottom: 1px solid black;"></view>
            <view class="login-btn">
				<view>
					<liu-rotating-menu :btnObj="btnObj" @click="click"></liu-rotating-menu>
				</view>
                <button class="btn-class" @click="chooseImg" :disabled="user.callCount >= 5">选择图片进行护照识别</button>
				 <button class="img-box" @click="chooseImg" :disabled="user.callCount >= 5">
					<image class="img"  v-for="item in imgArr" :src="item" @click="previewImg(item)" ></image>
				</button> 
				<text class="page-lable">识别结果:</text>
				 <view class="result-box">
					 <view class="content">
						 <!-- table-list:表格数组 数组里对象可自定义字段  -->
						 <cc-defineTable :table-list="tableArr"></cc-defineTable>
					 </view> 
				 </view> 
				 <text class="page-lable">评论:</text> 
				 <view class="say-box">
				     <piaoyi-comment-list :apprises="apprises"></piaoyi-comment-list> 
				 </view> 
				 <view class="say-box">
				 	<textarea v-model="newComment" placeholder="请输入评论内容"></textarea>
				 </view> 
				 <button class="btn-class" @click="submitComment">提交评论</button>
            </view>
        </view>
    </view>
</template>

<script>
	import piaoyiCommentList from '@/uni_modules/piaoyi-commentList/components/piaoyi-commentList/piaoyi-commentList.vue'
    export default {
		
		components: {
			piaoyiCommentList
		},
        data() {
            return {
				message : "识别成功!!!",
				lastDate: null,
				i:0,
                imgArr:[],
				 tableArr: [
					{ key: '姓名' ,value:''},
					{ key: '姓名拼音' ,value:''},
					{ key: '国籍' ,value:''},
					{ key: '性别' ,value:''},
					{ key: '生日' ,value:''},
					{ key: '出生地点' ,value:''},
					{ key: '签发日期' ,value:''},
					{ key: '护照号码' ,value:''},
					{ key: '签发机关' ,value:''},
					{ key: '护照签发地点' ,value:''},
					{ key: '国家码' ,value:''},
					{ key: '有效期至' ,value:''},
					{ key: 'MRZCode1' ,value:''},
					{ key: 'MRZCode2' ,value:''},
					],
				btnObj: {
					id: '1',
					name: '菜单',
					childs: [{
						id: '1',
						name: '主页'
					}, {
						id: '2',
						name: '用户'
					}, {
						id: '3',
						name: '识别'
					}]
				},
				newComment: '', // 新评论内容
				apprises: [],//评论列表
				user: {
				},
				history: [],//历史列表
				newHistory:'',
				
            }
        },
		created() {
		  this.apprises = uni.getStorageSync('apprises') || [];
		  this.user=uni.getStorageSync('user');
		  this.history = uni.getStorageSync('history') || [];
		  var count=uni.getStorageSync(this.user.id+"")
		  this.i=count;
		  this.$set(this.user, 'callCount', count);
		  console.log(count+"55555")
		  const lastDate = uni.getStorageSync('lastDate');
		  console.log("++++++++++++"+lastDate)
		  const currentDate = new Date().toLocaleDateString();
		  console.log("++++++++++++"+currentDate)
		  	
		  console.log(this.user.callCount+"============")
		  if (lastDate != currentDate) {

			  this.$set(this.user, 'callCount', 0);
			  uni.setStorageSync('user', this.user);
			  }
			  this.lastDate = currentDate;
		  },
        methods: {
			navigateToHistory(){
					uni.redirectTo({url:'/pages/index/history'});//关闭本页面然后路由跳转;
					console.log("-----进入历史页面-------")
			},
			submitComment() {
				
			  if (this.newComment.trim() !== '') {
			    const newCommentObj = { name: "账号："+this.user.username, 
										commentDate: new Date().toLocaleString(),
										 teachLevel: this.newComment };
			    this.apprises.push(newCommentObj); // 将新评论对象添加到评论列表数据中
			    uni.setStorageSync('apprises', this.apprises); // 存储评论列表到缓存
			    this.newComment = ''; // 清空评论输入框
			
			    // 提示评论提交成功或其他操作
			    uni.showToast({
			      title: '评论提交成功',
			      icon: 'none',
				  duration: 2000    //持续时间为 2秒
			    });
			  }
			},
            chooseImg() {
					// console.log("上传图片")
					uni.chooseImage({
						// 图片上传成功的回调函数
						success:res=>{
							// 当前这个数组中的值等于 得到的res 中的值，图片的路径
							this.imgArr = res.tempFilePaths;
							let result = this.getResult(this.imgArr[0]);
							this.$set(this.user, 'callCount', ++this.i);
							console.log("--------"+this.user.callCount)
							var count = this.user.callCount;
							uni.setStorageSync('user', this.user);
							uni.setStorageSync(this.user.id+"",count)
							
							//次数大于二十次提示
							if (this.user.callCount >= 5) {
								uni.showModal({
										title: "次数即将不足",
										content: "每天识别次数为5次，您的次数此次之后不足...",
										showCancel:false,
										success: function (res) {
											if (res.confirm) {
												console.log('用户点击确定');
											} else if (res.cancel) {
												console.log('用户点击取消');
											}
										}
									});
								// uni.setStorageSync('count', this.callCount);
								
								this.lastDate = new Date().toLocaleDateString();
								uni.setStorageSync('lastDate', this.lastDate);	
								return;
							}
						}
					})
				},
				//同步获取
			async getResult(img){
				let result = await uni.uploadFile({
				  url: "http://localhost:8200/passport/path",
				  filePath: img,
				  name: 'file'
				});
				let passportJson= JSON.parse(result[1].data);
				let passportResult = JSON.parse(passportJson.data);
				console.log(passportResult.error_code)
				if(passportResult.error_code!=null){
				if(passportResult.error_code==282103){
					
											uni.showModal({
													title: "非护照",
													content: "此图片非护照，识别失败!!!",
													showCancel:false,
													success: function (res) {
														if (res.confirm) {
															console.log('用户点击确定');
														} else if (res.cancel) {
															console.log('用户点击取消');
														}
													}
												});
					  const newHistoryObj ={name: "账号："+this.user.username, 
											commentDate: new Date().toLocaleString(),
											teachLevel: "此图片非护照，识别失败!!!" };
					  									 
					  this.history.push(newHistoryObj); 
					  uni.setStorageSync('history', this.history); 
					  this.$set(this, 'message', '识别成功!!!');

				}	
				if(passportResult.error_code==17){
						uni.showToast({
							title: '您的识别次数不足,识别失败!!!',
							icon: 'none',
							duration: 2000
						});
				}}else{	
				uni.showToast({
					title: '识别成功!!!',
					icon: 'none',
					duration: 2000
				});	
				this.passportMessage = passportResult.words_result;
				this.$set(this.tableArr[0], 'value', this.passportMessage.姓名.words);
				this.$set(this.tableArr[1], 'value', this.passportMessage.姓名拼音.words);
				this.$set(this.tableArr[2], 'value', this.passportMessage.国籍.words);
				this.$set(this.tableArr[3], 'value', this.passportMessage.性别.words);
				this.$set(this.tableArr[4], 'value', this.passportMessage.生日.words);
				this.$set(this.tableArr[5], 'value', this.passportMessage.出生地点.words);
				this.$set(this.tableArr[6], 'value', this.passportMessage.签发日期.words);
				this.$set(this.tableArr[7], 'value', this.passportMessage.护照号码.words);
				this.$set(this.tableArr[8], 'value', this.passportMessage.签发机关.words);
				this.$set(this.tableArr[9], 'value', this.passportMessage.护照签发地点.words);
				this.$set(this.tableArr[10], 'value', this.passportMessage.国家码.words);
				this.$set(this.tableArr[11], 'value', this.passportMessage.有效期至.words);
				this.$set(this.tableArr[12], 'value', this.passportMessage.MRZCode1.words);
				this.$set(this.tableArr[13], 'value', this.passportMessage.MRZCode2.words);
				// for(let i =0 ; i<14 ;i++){
				// 	if(this.tableArr[i].value.length>20){ 
				// 		this.$set(this.tableArr[i], 'value', this.passportMessage.MRZCode1.words.substr(0, 19)+"...");
				// 	}
				// }	
			
				//历史记录处理  	
				  for(let i =0 ; i< this.tableArr.length;i++){
					  if(this.tableArr[i].value==''){
						  this.$set(this, 'message', '有数据未识别到!!!');
					  }
				  }	
				  const newHistoryObj ={name: "账号："+this.user.username, 
										commentDate: new Date().toLocaleString(),
										teachLevel: this.tableArr[0].value+"的护照被识别一次，"+this.message };
				  console.log("----"+JSON.stringify(newHistoryObj))										 
				  this.history.push(newHistoryObj); 
				  
				  console.log(this.history+"-------------")
				  uni.setStorageSync('history', this.history); 
				  this.$set(this, 'message', '识别成功!!!');	
			}
			},
			previewImg (current) {	
				// 预览图片的方法
				uni.previewImage({
					// 当前需要预览的那张图片
					// current:current, 键和值相等可以缩写 current,
					current,
					// urls需要预览图片链接的列表
					urls:this.imgArr,
					// loop是否可循环预览，默认false
					loop:true,
					// indicator 图片底部为圆点default 顶部数字number 默认不显示none
					indicator:"number"
				})
			},
			//点击菜单
			click(e) {
				if(e.id=="1"){
					uni.showToast({
									title: "进入主页面",
									icon: 'success',    
									duration: 2000    //持续时间为 2秒
								})
					uni.redirectTo({url:'/pages/index/main'})//关闭本页面然后路由跳转
					// Router.push({ name:'main'}); 	 			
					console.log('所点击菜单信息：', e)
				}else if(e.id=="2"){
					uni.showToast({
									title: "进入用户页",
									icon: 'success',    
									duration: 2000    //持续时间为 2秒
								})
					uni.redirectTo({url:'/pages/index/users'})//关闭本页面然后路由跳转				
					console.log('所点击菜单信息：', e)
				}else{
					uni.showToast({
									title: "您已经在功能页面",
									icon: 'success',    
									duration: 2000    //持续时间为 2秒
								})
					
				}
							
			},
        }
    }
</script>

<style lang="scss" scoped>
    page {
        background: linear-gradient(to bottom, rgb(249, 249, 249) 0%, rgb(247, 246, 246) 100%);
    }

    .login-btn {
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }

    .btn-class {
		
        margin-top: 20px;
        width: 90vw;
        font-size: 14px;
        color: rgb(80, 80, 80);
        padding: 5px;
        background-color: #fff;
    }
    .page-lable{
        width: 90vw;
        padding: 10px 0;
        color: rgb(60,60,60)
    }
    .img-box{
		background-image: url('@/static/img/bg_photo.png');
		background-size: cover;
		margin-top: 10px;
        width: 90vw;
        min-height: 300rpx;
        border-radius: 5px;
        text-align: center;
        border: 1px solid rgb(220, 220, 220);
        background-color: #fff;
        
    }
	.result-box{
	    width: 90vw;
	    height: auto;
	    border-radius: 5px;
	    border: 1px solid rgb(220, 220, 220);
	    background-color: #fff;
	    
	}
	.result-box text{
		font-size: 25rpx;
	}
	.say-box{
	    width: 90vw;
	    height: auto;
		font-size: 35rpx;
	    border-radius: 5px;
	    border: 1px solid rgb(220, 220, 220);
	    background-color: #fff;
	    padding: 10px 0;
	}
	
    .img-box image{
        max-width: 90%;
		height: 400rpx;
        
    }
	 page {

			background-color: #f7f7f7;
		}

	.content {
		display: flex;
		flex-direction: column;

	}
</style>